package com.tianji.promotion.enums;

import com.tianji.promotion.annotations.MyLock;
import lombok.AllArgsConstructor;
import org.redisson.api.RLock;

@AllArgsConstructor
public enum MyLockStrategy {
    SKIP_FAST("快速结束") {
        @Override
        public boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            return lock.tryLock(0, myLock.leaseTime(), myLock.timeUnit());
        }
    },
    FAIL_FAST("快速失败") {
        @Override
        public boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            boolean isLock = lock.tryLock(0, myLock.leaseTime(), myLock.timeUnit());
            if (!isLock) {
                throw new RuntimeException("获取锁失败");
            }
            return true;
        }
    },
    KEEP_TRYING("一直重试") {
        @Override
        public boolean tryLock(RLock lock, MyLock myLock) {
            lock.lock(myLock.leaseTime(), myLock.timeUnit());
            return true;
        }
    },
    SKIP_AFTER_RETRY_TIMEOUT("重试超时后结束") {
        @Override
        public boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            return lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.timeUnit());
        }
    },
    FAIL_AFTER_RETRY_TIMEOUT("重试超时后失败") {
        @Override
        public boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException {
            boolean b = lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.timeUnit());
            if (!b) {
                throw new RuntimeException("获取锁失败");
            }
            return true;
        }
    };


    public abstract boolean tryLock(RLock lock, MyLock myLock) throws InterruptedException;

    private final String desc;
}
